package ruc.grs.ypytd.dao.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.Logger;

/*
 * @author chenwei
 * 
 * 数据库操作类
 */
public class DataStore {

	private Connection conn = null;

	private Statement stmt = null; // /第一个Statement
	private PreparedStatement smt = null;
	private static final Logger LOG = Logger.getLogger(DataStore.class);

	// 这里最好从文件读取参数，比如.properties文件
	public DataStore() { // 初始化构造函数,conn
		try {
			Class.forName("org.objectweb.rmijdbc.Driver").newInstance();
			String url = "jdbc:odbc:ypy";
			String rmiHost = new String("//202.112.126.175");
			conn = DriverManager.getConnection("jdbc:rmi:" + rmiHost + "/"
					+ url);
		} catch (Exception e) {
			LOG.error("DataStore(String)", e);
		}

	}

	// 执行查询
	synchronized public ResultSet query(String sql) {
		ResultSet tmp = null;

		try {
			stmt = conn.createStatement();
			tmp = stmt.executeQuery(sql);

		} catch (SQLException e) {
			// System.out.println(e.getMessage());
			LOG.error("DataStore(String)", e);
		}
		return tmp;
	}

	// 执行修改，插入
	synchronized public void executeUpdate(String sql) {
		try {
			stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
					ResultSet.CONCUR_UPDATABLE);

			stmt.executeUpdate(sql);

		} catch (SQLException e) {
			// e.printStackTrace();
			LOG.error("DataStore(String)", e);
		}
	}

	synchronized public PreparedStatement getstatement(String sql) {
		try {
			smt = conn.prepareStatement(sql);

		} catch (SQLException e) {
			LOG.error("DataStore(String)", e);
			// e.printStackTrace();
		}
		return smt;
	}

	synchronized public void close() {
		try {
			if (stmt != null) {
				stmt.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (Exception e) {
			/* 记录到日志 */
			System.out.println(e.getMessage());
			LOG.error("DataStore(String)", e);
		} finally {
			conn = null;
		}
	}

}